package student.aistar.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import student.aistar.mapper.CartMapper;
import student.aistar.model.dto.CartProductDTO;
import student.aistar.model.entity.Cart;
import student.aistar.model.entity.Product;
import student.aistar.service.ICartService;
import student.aistar.service.IProductService;

import java.util.ArrayList;
import java.util.List;

/**
 * 本类用来演示:
 *
 * @author: qinFeng
 * @date: 2021/9/27 10:04
 */
@Service
public class CartService implements ICartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    IProductService productService;






    @Override
    public List<Cart> userCart(Integer id) {
        return cartMapper.selectCartByUserId(id);
    }

    @Override
    public void deleteCartProduct(Integer id) {
        cartMapper.deleteCartById(id);
    }

    @Override
    public CartProductDTO goToSettle(Integer userId, String productIds, String Nums, String paraList) {
        //将勾选的产品放入到一个集合
        List<Product> productList = new ArrayList<>();
        //将勾选产品的小计放入到一个集合
        List<Cart> cartList = new ArrayList<>();

        Integer countProducts = 0;
        Double totalPrices = 0.0;
        String[] proIdArr = productIds.split(":");
        String[] numsArr = Nums.split(":");
        String[] paraArr = paraList.split(":");
        for (int i = 0; i < proIdArr.length; i++) {
            Product product = productService.findById(Integer.valueOf(proIdArr[i]));
            productList.add(product);

            cartMapper.updateCart(product.getPrice(), (Integer.valueOf(numsArr[i])), userId, product.getProductId(), paraArr[i]);

            Cart cart = cartMapper.selectCart(userId, product.getProductId(), paraArr[i]);
            cartList.add(cart);

            countProducts += cartList.get(i).getNum();
            totalPrices += cart.getTotalprice();
        }

        CartProductDTO cartProductDTO = new CartProductDTO();
        cartProductDTO.setCartList(cartList);
        cartProductDTO.setProductList(productList);
        cartProductDTO.setCountProducts(countProducts);
        cartProductDTO.setTotalPrices(totalPrices);
        return cartProductDTO;
    }




    @Override
    public Cart selectByUserIdAndProductId(Integer userId, Integer productId, String paraName) {
        return cartMapper.selectCart(userId, productId, paraName);
    }

    @Override
    public void addCart(Cart cart) {
        cartMapper.addCart(cart);
    }

    @Override
    public void updateCart(double price, Integer num, Integer userId, Integer productId, String paraName) {
        cartMapper.updateCart(price, num, userId, productId, paraName);
    }

    @Transactional
    @Override
    public Cart findUserCheckCart(Integer id) {
        return cartMapper.selectCartById(id);
    }


}
